var saleApplicationDetailsWindow = new Ext.Window({	
		layout : 'fit',
		border : false,
		title : 'Детали заявки',
		closeAction : 'hide',	
		y : 50,
		width : 340,
		autoHeight : true,
		bodyStyle : "background-color:#CCD8E7",		
		items : [new Ext.FormPanel({
					border : false,
					bodyStyle : "background-color:#CCD8E7",
					height : 450,
					items : [new Ext.form.TextField({fieldLabel : "Фамилия",
													 readOnly : true,
													 id : "saleAppLastName",
													 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Имя",
								 					 readOnly : true,
								 					 id : "saleAppFirstName",
								 					 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Отчество",
								 					 readOnly : true,
								 					 id : "saleAppPatronymik",
								 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Телефон",
						    	 					 readOnly : true,
						    	 					 id : "saleAppPhone",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "E-mail",
						    	 					 readOnly : true,
						    	 					 id : "saleAppEmail",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Район",
						    	 					 readOnly : true,
						    	 					 id : "saleAppDistrict",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Этаж",
						    	 					 readOnly : true,
						    	 					 id : "saleAppFloor",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Этажей",
							   	 					 readOnly : true,
							   	 					 id : "saleAppFloorsCount",
							   	 					 width : 210}),	 					 
						     new Ext.form.TextField({fieldLabel : "Комнат",
						    	 					 readOnly : true,
						    	 					 id : "saleAppRooms",
						    	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Площадь",
							   	 					 readOnly : true,
							   	 					 id : "saleAppSquare",
							   	 					 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Жилая площадь",
							   	 					 readOnly : true,
							   	 					 id : "saleAppLivingSpace",
							   	 					 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Площадь кухни",
							   	 					 readOnly : true,
							   	 					 id : "saleAppCookSpace",
							   	 					 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Улица",
							   	 					 readOnly : true,
							   	 					 id : "saleAppStreet",
							   	 					 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Дом",
							   	 					 readOnly : true,
							   	 					 id : "saleAppHouse",
							   	 					 width : 210}),
							 new Ext.form.TextField({fieldLabel : "Квартира",
							   	 					 readOnly : true,
							   	 					 id : "saleAppFlat",
							   	 					 width : 210}),
						     new Ext.form.TextField({fieldLabel : "Цена",
						    	 					 readOnly : true,
						    	 					 id : "saleAppPrice",
						    	 					 width : 210})
						     ]
				 })]
});

var meetingFlatsStore = new Ext.data.JsonStore({
	url : "/flats/realtor/get_flats_for_meeting.do",	
	fields : ["flat.street","flat.house","flat.flat","flat.id","status","id"]
});

function showDetails(id) {
	Ext.Ajax.request({
		url : "/flats/realtor/get_application_details.do",
		method : 'post',
		params : {optionsId:id},
		success : function(response) {
			var data = Ext.decode(response.responseText);		
				Ext.getCmp("saleAppLastName").setValue(data.client.lastName);
				Ext.getCmp("saleAppFirstName").setValue(data.client.firstName);
				Ext.getCmp("saleAppPatronymik").setValue(data.client.patronymik);
				Ext.getCmp("saleAppPhone").setValue(data.client.phone);
				Ext.getCmp("saleAppEmail").setValue(data.client.email);
				Ext.getCmp("saleAppDistrict").setValue(data.flat.district.name);
				Ext.getCmp("saleAppFloor").setValue(data.flat.floor);
				Ext.getCmp("saleAppFloorsCount").setValue(data.flat.floors);
				Ext.getCmp("saleAppRooms").setValue(data.flat.rooms);
				Ext.getCmp("saleAppSquare").setValue(data.flat.square);
				Ext.getCmp("saleAppLivingSpace").setValue(data.flat.livingSquare);
				Ext.getCmp("saleAppCookSpace").setValue(data.flat.cookSquare);
				Ext.getCmp("saleAppStreet").setValue(data.flat.street);
				Ext.getCmp("saleAppHouse").setValue(data.flat.house);
				Ext.getCmp("saleAppFlat").setValue(data.flat.flat);
				Ext.getCmp("saleAppPrice").setValue(data.flat.price);
				saleApplicationDetailsWindow.show();			
		},
		failure : function() {
			Ext.Msg.alert("Ошибка","Не могу получить данные о заявке!\nПопробуйте позже.");
		}
	});	
}

var createMeetingFlatsPanel = new Ext.Panel({
	border : false,
	bodyStyle : "margin-left: 20px",
	autoHeight : true,
	items : [new Ext.grid.GridPanel({
				 store : meetingFlatsStore,
				 columnLines : true,	
				 viewConfig : {forceFit : true},
				 height : 470,		 							 
				 width : 620,
				 selModel : new Ext.grid.RowSelectionModel({
 		 		 singleSelect : true,
 				 listeners : {
 					 rowselect : {
 						fn : function(sm,index,record) { 							  						
 									Ext.getCmp("createMeetingOptionId").setValue(record.data.id); 							  						
 				  			 }
 					    }
 				 	}
		 	     }),		 	
		 	     columns : [{sortable : true,header : "Улица",dataIndex : "flat.street"},
		 		            {sortable : true,header : "Дом",dataIndex : "flat.house"},
		 		            {sortable : true,header : "Квартира",dataIndex:"flat.flat"},
		 		            {sortable : true,header : "Статус",dataIndex:"status",renderer : function(val){
		 							            	switch(val) {
		 							            		case "GOOD" : return "Хорошо"; break;
		 							            		case "BAD" : return "Плохо"; break;
		 							            		case "NORMAL" : return "Нормально"; break;
		 							            		case "NONE" : return "";break;
		 							            	}
		 		            }},
		 		            {sortable : false,header : "Подробнее",renderer : function(val,object,row) {
		 						            	var button = "<button onclick='showDetails("+row.data['id']+")'>Подробнее</button>";
		 						            	return button;
		 		            }},		 							            
		 		            {hidden:true,hideable:false,dataIndex:"OPTIONSID"}]})]		 							 						            
});
var meetingsStore = new Ext.data.JsonStore({
	url : "/flats/realtor/get_meetings.do",
	fields : ["option.flat.street","option.flat.house","option.flat.flat","date","id","status"]	
});
var createMeetingPanel = new Ext.Panel({
	bodyStyle: "padding:10px",
	layout : 'hbox',
	layoutConfig: {
	    align : 'stretch',
	    pack  : 'start'
	},
	items :[new Ext.FormPanel({border :false,	
							   url : "/flats/realtor/create_meeting.do",
							   id : "createMeetingForm",
							   items : [new Ext.form.DateField({fieldLabel : "Дата",
								   							    allowBlank : false,								   							    
								   							    id : "createMeetingDate",
								   							    width : 150}),
								   	    new Ext.form.TimeField({fieldLabel : "Время",
								   	    						minValue: '9:00',
								   	    						maxValue: '20:00',
								   	    					    format:'H:i', 
								   	    					    allowBlank : false,
								   	    						increment: 10,
								   	    						id : "createMeetingTime",
								   	    						width : 150}),
								   	    new Ext.form.Field({hidden : true,					
								   	    						name : "option.id",
								   	    	                    id:"createMeetingOptionId",
								   	    	                    allowBlank : false}),
                                        new Ext.form.Field({hidden : true,
                                        	                 name : "date",
                                        	                 id : "meetingDate",
                                        	                 allowBlank : false}),
								   	    new Ext.Button({text : "Создать",
									   				   handler : function() {									   					  
									   					   			var form = Ext.getCmp('createMeetingForm');
									   					   			var date = Ext.getCmp("createMeetingTime").value + " " + 
									   					   			           Ext.getCmp("createMeetingDate").value;
									   					   			Ext.getCmp("meetingDate").setValue(date);
									   					   			if (form.getForm().isValid()) {									   					   								   					   				
									   					   				form.getForm().submit({
									   					   					success : function(request,response) {
									   					   						var data = Ext.decode(response.response.responseText);
									   					   						if (data.copy) {
									   					   							Ext.Msg.alert("Ошибка","На данное время уже назначена встреча!");
									   					   						} else if (data.error) {
									   					   							Ext.Msg.alert("Ошибка","Не могу добавить встречу. Попробуйте позже!");
									   					   						} else {
									   					   							meetingsStore.reload();
									   					   							Ext.Msg.alert("Добавлено","Встреча успешно добавлена");
									   					   						}
									   					   					},
									   					   					failur : function() {
									   					   						Ext.Msg.alert("Ошибка","Не могу добавить встречу. Попробуйте позже!");
									   					   					}
									   					   				});
									   					   			}
									   	    				     }
									   	    })]}),
		 createMeetingFlatsPanel]
});

var createMeetingWindow = new Ext.Window({	
			layout : 'fit',
			border : false,
			title : 'Создать встречу',
			closeAction : 'hide',	
			y : 50,
			width : 940,
			height : 535,
			bodyStyle : "background-color:#CCD8E7",
			modal : true,
			items : [createMeetingPanel]
});


var deleteMeetingId = new Ext.form.Field({hidden:true});

function deleteMeeting(id) {
	deleteMeetingId.setValue(id);
	Ext.Msg.show({
		  title : "Удалить",
		  msg : "Вы уверены, что хотите удалить встречу?",
		  buttons : Ext.Msg.YESNO,
		  fn : function(btn) {
			if (btn == "yes") {				
				Ext.Ajax.request({
					url : "/flats/realtor/delete_meeting.do",
					method : "post",
					params : {id : deleteMeetingId.getValue()},
					success : function(response) {
						var data = Ext.decode(response.responseText);
						if (data) {
							meetingsStore.reload();
							Ext.Msg.alert("Удалено","Встреча успешно удалена!");
						} else {
							Ext.Msg.alert("Ошибка","Не могу удалить встречу! Попробуйте позже");	
						}
					},
					failure : function(){
						Ext.Msg.alert("Ошибка","Не могу удалить встречу!\nПопробуйте позже");
					}
				});
			} 
		  },
		  animEl : 'elId',
		  icon : Ext.MessageBox.QUESTION
	});
}
var finishMeetingData = [["Хорошо","GOOD"],["Плохо","BAD"],["Нормально","NORMAL"]];
var finishMeetingComboBox = new Ext.form.ComboBox({
	store : new Ext.data.ArrayStore({fields : [{name:"name"},{name:"value"}]}),	
	displayField : 'name',
	valueField : 'value',
	mode : 'local',		
	fieldLabel : 'Впечатления',
	width :210,	
	allowBlank : false,
	hiddenName : "option.status"
});
var finishMeetingId = new Ext.form.Field({hidden : true,name:"id"});
var finishMeetingForm = new Ext.FormPanel({
	url : "/flats/realtor/finish_meeting.do",
	bodyStyle : "padding:10px;background-color:#CCD8E7",		
	border : false,
	items :[finishMeetingComboBox,finishMeetingId],
	buttons : [new Ext.Button({text : "Завершить",
				   handler : function() {
					  if(finishMeetingForm.getForm().isValid()) {
						  finishMeetingForm.getForm().submit({
							success : function() {
								   meetingsStore.reload();
							       finishMeetingWindow.hide();
								   finishMeetingComboBox.reset();
							}
						   });
					  }
			   }}),
	           new Ext.Button({text : "Отмена",
	  	   			   handler : function(){
	     	   				   finishMeetingWindow.hide();
	    	   }})]
});

var finishMeetingWindow = new Ext.Window({	
		layout : 'fit',
		border : false,
		title : 'Выберите тип заявки',
		closeAction : 'hide',	
		y : 50,
		width : 350,
		height : 105,
		bodyStyle : "background-color:#CCD8E7",
		modal : true,
		items : [finishMeetingForm]
});


function finishMeeting(id) {
	finishMeetingWindow.show();
	finishMeetingId.setValue(id);
	finishMeetingComboBox.getStore().loadData(finishMeetingData);
}

var meetingsTypeWindow = new Ext.Window({	
	layout : 'fit',
	border : false,
	title : 'Встречи',
	closeAction : 'hide',	
	y : 50,
	width : 940,
	height : 505,
	bodyStyle : "background-color:#CCD8E7",
	modal : true,
	items : [new Ext.Panel({autoHeight : true,
					border : false,
				    items : [new Ext.Panel({border : false,
		    					    tbar:[new Ext.Button({text : "Создать встречу",
	   					    					  handler : function(){
	   					    						  meetingFlatsStore.load({params:{applicationId:currentActiveOrderId.getValue()}});
	  					    						  createMeetingWindow.show();
				    					  }})]
						     }),
							   		               
			 new Ext.grid.GridPanel({border : false,
					columnLines : true,	
					height : 470,
					store : meetingsStore,
					viewConfig : {forceFit : true},
					columns : [{sortable : true,header : "Время",dataIndex :"date"},
							   {sortable : true,header : "Улица",dataIndex : "option.flat.street"},
							   {sortable : true,header : "Дом",dataIndex : "option.flat.house"},
							   {sortable : true,header : "Квартира",dataIndex : "option.flat.flat"},
							   {dataIndex : "id",hidden:true,hideable:false},
							   {dataIndex : "status",hidden:true,hideable:false},
							   {sortable : false,header : "Завершить",renderer:function(val,object,row){
							       	var button = "<button onclick='finishMeeting("+row.data['id']+")'";
							       	if (row.data['status'] == "FINISHED") {
							      		button += " disabled ";
							       	}
							       	button += ">Завершить</button>";
							       	return button;
							   }},
							   {sortable : false,header : "Редактировать",renderer : function(val,object,row){
							       	var button = "<button onclick='deleteMeeting("+row.data['id']+")'";
							       	if (row.data['status'] == "FINISHED") {
							          		button += " disabled ";
							       	}
							       	button += ">Удалить</button>";
							       	return button;
							   }}]
			})]})]
});
var currentActiveOrderId = new Ext.form.Field({hidden : true});

function showMeetingsWindow(id) {
	currentActiveOrderId.setValue(id);
	meetingsStore.load({params:{applicationId:id}});
	meetingsTypeWindow.show();
}

var applicationsStore = applicationsStoreFactory.createApplicationStore("/flats/realtor/get_applications.do");

var applicationsGrid = new Ext.grid.GridPanel({	
		store : applicationsStore,
		columnLines : true,	
		height : 600,
		border:false,
		viewConfig : {forceFit : true},
		columns : [{sortable : true,dataIndex:'id',header : "Номер заявки"},
		           {sortable : true,dataIndex:'createDate',header:'Дата'},
		           {sortable : true,dataIndex:'client.lastName',header:'Фамилия'},
		           {sortable : true,dataIndex:'client.firstName',header:'Имя'},
		           {sortable : true,dataIndex:'client.patronymik',header:'Отчество'},
		           {sortable : true,header:'Встречи',renderer: function(val,object,row){
		        	   return "<button onclick='showMeetingsWindow("+row.data['id']+
		        	   ")'>Встречи</button>";		        	   
		           }}],
		bbar : new Ext.PagingToolbar({
			pageSize : 20,
			store : applicationsStore
		})
});

var applicationsWindow = new Ext.Window({
		layout : 'fit',
		title : 'Заявка',
		closeAction : 'hide',	
		x : 10,
		y : 35,
		width : 1260,
		autoHeight : true,
		viewConfig : {forceFit : true},
		items : [ new Ext.Panel({border:false,
								 autoHeight : true,
							     viewConfig : {forceFit : true},
							     items :[applicationsGrid]}) ]
});

var meetingsWindow = new Ext.Window({
	layout : 'fit',
	title : 'Встречи',
	closeAction : 'hide',	
	x : 10,
	y : 35,
	width : 1260,
	autoHeight : true,
	viewConfig : {forceFit : true},
	items : [ new Ext.Panel({border:false,
							 autoHeight : true,
						     viewConfig : {forceFit : true},
						     items :[new Ext.Panel({
						    	        border : false,
		    					    	tbar:[" ",
		    					    	      new Ext.form.Label({
		    					    		    text : "Выберите дату:"		    					    		    
		    					    		  }),
		    					    		  " ",
		    					    	      new Ext.form.DateField({
		    					    			fieldLabel : "Дата",
				   							    allowBlank : false,								   							    
				   							    id : "findMeetingsDate",
				   							    width : 150}
		    					    	      ),
		    					    	      " ",
		    					    	      new Ext.Button({
		    					    	    	  text : "Показать",
		    					    	    	  handler : function () {
		    					    	    		  Ext.Ajax.request({
		    					    	    			  url : "/flats/realtor/get_meetings_by_date.do",
		    					    	    			  method : "post",
		    					    	    			  params : {date : Ext.getCmp("findMeetingsDate").value},
		    					    	    			  success : function(response) {
		    					    	    				  alert("D");
		    					    	    			  }
		    					    	    		  });
		    					    	    	  }
		    					    	      })]
						    })]})]
});

Ext.onReady(function() {
	Ext.QuickTips.init();
	var applicationMenu = new Ext.Panel({
		border :false,
		viewConfig : {forceFit : true},
		tbar:[new Ext.Button({text : "Заявки",
				  		      handler : function() {
				  		    	applicationsStore.load({params:{start:0,limit:20}});
				  		    	applicationsWindow.show();
				  		      }}),	  		      
				  		      '-',
              new Ext.Button({text : "Встречи",
            	              handler : function (){
            	            	  meetingsWindow.show();
            	              }}),
              				  '->',
			  new Ext.Button({text : 'Выход',
				  			  handler : function() {
				  				  Ext.Msg.show({
				  					  title : "Выход",
				  					  msg : "Вы уверены, что хотите выйти?",
				  					  buttons : Ext.Msg.YESNO,
				  					  fn : function(btn) {
											if (btn == "yes") {							
												document.location.href="http://localhost:8080/flats/app/logout";
											} 
				  					  },
				  					  animEl : 'elId',
				  					  icon : Ext.MessageBox.QUESTION
				  				  });
				  			  }})],
		height : 20,
		renderTo : Ext.get("menu")
	});	
});